// 导入
import http from 'wechat-http'
// 设置请求根路径
http.baseURL = 'https://live-api.itheima.net'
/**
 * 请求拦截器
 */
http.intercept.request = (config) => {
   const app = getApp()
   if(app.token){
      config.header = {
         Authorization : `Bearer ${app.token}`,
         ...config.header
      }
      // console.log('333333333',config.header);
   }
   return config
}
/**
 * 响应拦截器
 */
http.intercept.response = async (res) => {
   // 处理401的情况
   console.log('999999999999',res);
  const app = getApp()
  if(res.statusCode === 401){
   if(res.config.url.includes('/refreshToken')){
      const pages = getCurrentPages()
      const currect = pages[pages.length - 1]
      wx.navigateTo({url:"/pages/login/index?redirect=" + currect.route})
      return
   }
   const results = await wx.http({
    url:'/refreshToken',
    method:'post',
    header:{
      Authorization : `Bearer ${app.refreshToken}`
    }
  })
  console.log(results);
  const {token,refreshToken} = results.data
  app.setToken(token,refreshToken)
  //无感刷新
 return wx.http({
   ...res.config,
   header:{
      Authorization:`Bearer ${app.token}`
   }
  })
  }
   // 解构data
   if(res.data.code === 10000){
    return res.data
   }else{
    return Promise.reject()
   }
}
// 全局挂载
wx.http = http
// 默认导出
export default http